import React from 'react';
import PropTypes from 'prop-types';
import 'whatwg-fetch';
// style
import CSSModules from 'react-css-modules';
import styles from './qiniu.scss';

@CSSModules(styles)
export default class Qiniu extends React.Component {

  static defaultProps = {
    text: '上传图片',
    size: 1024*1024*2,
    accept: '*',
    multiple: true,
    uploadUrl: (()=>{
      if (typeof window == 'undefined' || typeof document == 'undefined') return '';
      return window.location.protocol === 'https:' ? 'https://up.qbox.me/' : 'http://upload.qiniu.com';
    })(),
    onUpload: (file)=>{}
  }

  static propTypes = {
    token: PropTypes.string,
  }

  constructor(props) {
    super(props);
    this.state = {};
    this.onChange = this.onChange.bind(this);
    this.upload = this.upload.bind(this);
  }

  onChange(e) {

    e.preventDefault();

    const self = this;

    let files;
    if (e.dataTransfer) {
      files = e.dataTransfer.files;
    } else if (e.target) {
      files = e.target.files;
    }

    let maxFiles = (this.props.multiple) ? files.length : 1;

    let arr = [];

    for (var i = 0; i < maxFiles; i++) {
      files[i].preview = URL.createObjectURL(files[i]);
      console.log(URL, 'url')
      files[i].upload = ((file)=>{
        console.log(file, 'file')
        return () => self.upload(file)
      })(files[i]);

      arr.push(files[i]);
    }

    this.props.onUpload(arr);
  }

  upload(file) {

    if (!file || file.size === 0) return null;

    const key = file.preview.split('/').pop() + '.' + file.name.split('.').pop();

    return new Promise(resolve=>{

      const input = document.querySelector('input[type="file"]');
      const data = new FormData();
      data.append('file', file);
      data.append('token', this.props.token);
      data.append('key', key);
      data.append('x:filename', file.name);
      data.append('x:size', file.size);

        var COS = require('cos-js-sdk-v5');
        // 车海洋
        var cos = new COS({
            SecretId: 'AKID9RcbQ3gxIRODqLdolV3PeO7hHj18tlGZ',
            SecretKey: 'GNJ2Zu35UoxuKcl2B9vVu78FJD1d8Uec',
        });
        // // Allon
        // var cos = new COS({
        //     SecretId: 'AKIDkdP4Zte5TpJrU3mdq5FINPHycBZpi11x',
        //     SecretKey: '0rX8YBd3KTRHwTzQgrsfMvLadVCqNky7',
        // });
        // 整文件上传  Allon  2018年11月9日17:23:22
        cos.putObject({
            // Bucket: 'chyweimob-1253630189', // 桶名-APPID  必须
            Bucket: 'chy-ds-1253882812', // 桶名-APPID  必须
            Region: 'ap-guangzhou', //区域 必须
            Key: file.name, //文件名必须
           // StorageClass: 'STANDARD',
            Body: file, // 上传文件对象
            onProgress: function (progressData) {
                console.log(JSON.stringify(progressData));//上传成功的返回值
                resolve(file.name)//上传成功传递文件名
            }
        }, function (err, data) {
            console.log(err || data);//上传失败的返回值
            resolve(data)
        });
    });

  }

  render() {

    const { text, accept, multiple } = this.props

    return (<a href="javascript:void(0)" styleName="file">{text}<input type="file" accept={accept} multiple={multiple} onChange={this.onChange} /></a>)
  }

}
